package com.cgl.controller;

import com.auth0.jwt.interfaces.Claim;
import com.cgl.pojo.LeaveMessage;
import com.cgl.pojo.Result;
import com.cgl.service.LeaveMessageService;
import com.cgl.until.JwtUntil;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;


@RestController
public class LeaveMessageController {
    private static final Logger logger = LoggerFactory.getLogger(LeaveMessageController.class);

    @Autowired
    private LeaveMessageService leaveMessageService;
    @PostMapping("api/leaveMessage/add")
    public Result addLeaveMessage(HttpServletRequest request, @RequestBody LeaveMessage leaveMessage){
        logger.info("添加留言:{}",leaveMessage);

        String token;
        try {
            token = request.getHeader("LY-Authorization").replace("\"", "");
        }catch (NullPointerException e){
            return Result.error("用户未登录");
        }
        logger.info("用户登录:{}", token);

        if (!JwtUntil.verifyToken(token)){
            return Result.error("timeover");
        }

        Map<String, Claim> data = JwtUntil.decodeToken(token);

        logger.info("解码的JWT声明: {}", data);

        String userId = data.get("userId").asString();

        if (leaveMessage.getContent().equals("")){
            return Result.error("留言内容不能为空");
        }
        String ip = request.getRemoteAddr();

        leaveMessage.setIp(getIPv4Address(ip));
        leaveMessage.setUserName(userId);

        int result = leaveMessageService.addLeaveMessage(leaveMessage);
        if (result>0){
            return Result.success();
        }else {
            return Result.error("添加失败");
        }
    }

    private static String getIPv4Address(String ip) {
        // 如果是IPv6的本地回环地址，直接返回IPv4的本地回环地址
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            return "127.0.0.1";
        }
        // 如果是IPv6的映射IPv4地址，提取IPv4部分
        if (ip.contains(":")) {
            int ipv4PartIndex = ip.lastIndexOf(':');
            ip = ip.substring(ipv4PartIndex + 1);
        }
        return ip;
    }

    @GetMapping("leaveMessage/getlist")
    public Result getLeaveMessageList(){
        logger.info("获取留言");
        List<LeaveMessage> leaveMessageList = leaveMessageService.getAllLeaveMessage();
        return Result.success(leaveMessageList);
    }

    @GetMapping("leaveMessage/getinfo")
    public Result getLeaveMessageCount(){
        logger.info("获取留言数量");
        int count = leaveMessageService.getAllConunt();
        return Result.success(count);
    }
}
